/*
 * @lc app=leetcode.cn id=234 lang=cpp
 *
 * [234] 回文链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        //1.
        //将所有元素放入容器, 然后双指针
        //时间复杂度 O(2n) = O(n), 空间复杂度 O(n)

        //2.
        //将后半部分链表反转, 然后双指针
        //空间复杂度 O(1)

        if (head == nullptr || head->next == nullptr)
            return true;

        ListNode* slow = head;
        ListNode* fast = head;

        //快慢指针得到 slow 中间节点
        for (; fast->next != nullptr;) {
            if (fast->next->next == nullptr)
                break;

            fast = fast->next->next;
            slow = slow->next;
        }


        //反转链表(修改原链表了)
        ListNode* reverseListHead = slow->next; //反转链表头节点
        slow->next = nullptr;
        ListNode* next = slow;   //使用一个节点记录 next
        while (reverseListHead != nullptr) {
            auto temp = reverseListHead;
            reverseListHead = reverseListHead->next;
            temp->next = next;
            next = temp;
        }
        reverseListHead = next;

        //检查是否回文
        for (; head != slow->next; head = head->next, reverseListHead = reverseListHead->next) {
            if (head->val != reverseListHead->val)
                return false;
        }

        return true;
    }
};
// @lc code=end

